package com.xyhuo.leetcode.january;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 逆波兰表达式求值
 * https://leetcode.cn/problems/evaluate-reverse-polish-notation/
 *
 * @time 2024/1/19
 */
public class EvalRPN {

//    public static void main(String[] args) {
//        EvalRPN eRPN = new EvalRPN();
//        String[] tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
//        eRPN.evalRPN(tokens);
//    }

    public int evalRPN(String[] tokens) {
        String[] symbols = {"+", "-", "*", "/"};
        Deque<Integer> deque = new ArrayDeque<>();
        for (String token : tokens) {
            boolean isNum = token.matches("-?[0-9]+");
            if (isNum) {
                deque.addLast(Integer.parseInt(token));
            } else {
                Integer two = deque.removeLast();
                Integer one = deque.removeLast();
                if (symbols[0].equals(token)) {
                    deque.addLast(one + two);
                } else if (symbols[1].equals(token)) {
                    deque.addLast(one - two);
                } else if (symbols[2].equals(token)) {
                    deque.addLast(one * two);
                } else if (symbols[3].equals(token)) {
                    deque.addLast(one / two);
                }
            }
        }
        return deque.removeLast();
    }
}
